package com.zxf.course.service.impl;

import java.io.IOException;
import java.sql.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zxf.course.bean.Student;
import com.zxf.course.commonutils.TimeConvert;
import com.zxf.course.service.ExcelOperateService;
import com.zxf.course.service.StudentService;
@Service
public class ExcelOperateServiceImpl implements ExcelOperateService {
	@Autowired
	private StudentService studentService;
	
	public void exportExcel(String[] titles, ServletOutputStream out) {
		// 第一步，创建一个workbook，对应一个Excel文件
		HSSFWorkbook workbook = new HSSFWorkbook();
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet hssfSheet = workbook.createSheet("学生信息表");
		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow hssfRow = hssfSheet.createRow(0);
		// 第四步，创建单元格，并设置值表头 设置表头居中
		HSSFCellStyle hssfCellStyle = workbook.createCellStyle();
		// 居中样式
		hssfCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

		HSSFCell hssfCell = null;
		for (int i = 0; i < titles.length; i++) {
			hssfCell = hssfRow.createCell(i);// 列索引从0开始
			hssfCell.setCellValue(titles[i]);// 列名1
			hssfCell.setCellStyle(hssfCellStyle);// 列居中显示
		}
		
		List<Student> stuList = studentService.selectStudentList();
		for (Student student : stuList) {
			System.out.println(student);
		}
		// 第五步根据返回的实体创建行和列，并填充各个单元格的值
		for (int i = 0; i < stuList.size(); i++) {
			Student student = stuList.get(i);
			hssfRow = hssfSheet.createRow(i + 1);
			hssfRow.createCell(0).setCellValue(student.getStudentNo());
			hssfRow.createCell(1).setCellValue(student.getStudentName());
			hssfRow.createCell(2).setCellValue(student.getStudentContact());
			hssfRow.createCell(3).setCellValue(student.getClasses().getClassName());
			hssfRow.createCell(4).setCellValue(TimeConvert.convertUtilToSql(student.getAddTime())+"");
		}
		// 第六步，将文件输出到客户端浏览器
		try {
			workbook.write(out);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
